<?php
    require "../init.php";



    // 验证表单数据是否为空;
    foreach($_POST as $key){
        if(empty($key)){
            redirect("表单数据不能为空");
            die;
        }
    }

    //判断验证码是否正确;都转换成小写在进行比较;
    $vcode = strtolower($_SESSION['code']);// 创建验证码是传进session中的
    $uservcode = strtolower($_POST['vcode']);//从注册表单传过来的
    if($vcode != $uservcode){
        redirect("验证码不正确");
        die;
    }

    //接受参数
    $name = $_POST['name'];
    $pwd = md5($_POST['pwd']);


    $regex_name = '/^[a-zA-Z]\w{3,14}$/';
    if(!preg_match($regex_name, $name)){
        redirect("用户名格式不正确");
        die;
    }

    //查询数据库该用户名是否已经存在

    $sql = "select id,name,pwd,logincount from " . PRE ."user where name = '" . $name . "' limit 1";
    //接受查询结果
    $result = getRow($link, $sql);

    //如果没有该用户会返回false;
    if(!$result){
        redirect("该用户名不存在");
        die;
    }else{
        if($pwd == $result['pwd']){// 对密码进行比较
            unset($_SESSION['code']);
            unset($result['pwd']);
            //登录成功之后,把用户信息放进session中
            $_SESSION['home'] = $result;
            //把用户头像名称放入session中
            $sql = "select head_image from ".PRE."user_head where user_id= '".$result['id']."'";
            $res = getRow($link, $sql);
            $_SESSION['home']['head_image'] = $res['head_image'];
            //登录成功,logincount+1 登录次数；
            $num = $result['logincount'] + 1;
            $sql = "update " . PRE . "user set logincount = $num where name = '" . $name . "'";
            $res = execute($link, $sql);
            if($res){
                redirect("登录成功", 3, ROOT_URL."index.php");
                die;
            }

        }else{
            redirect("密码错误");
            die;
        }


    }



 ?>